from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group

User = get_user_model()

ENV_TYPE = (
    ('dev', '开发环境'),
    ('test', '测试环境'),
    ('prod', '生产环境'),
)


class DatabaseConfig(models.Model):

    name = models.CharField(verbose_name='数据库名', max_length=32, help_text='连接的数据库database名称')
    host = models.CharField(verbose_name='数据库地址', max_length=32, help_text='数据库连接地址')
    port = models.IntegerField(verbose_name='数据库端口', help_text='数据库连接端口')
    user = models.CharField(verbose_name='数据库用户', help_text='数据库授权连接的用户', max_length=64)
    password = models.CharField(verbose_name='数据库密码', max_length=128)
    env = models.CharField(verbose_name='所属环境', help_text='数据库连接端口', choices=ENV_TYPE, max_length=12)
    utime = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    ctime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    remark = models.TextField(default='', null=True, blank=True, verbose_name='备注')

    def __str__(self):
        return '{}-{}'.format(self.host, self.name)

    class Meta:
        ordering = ['-id']


class AuditSQL(models.Model):
    STATUS = (
        (-3, '已回滚'),
        (-2, '已暂停'),
        (-1, '待执行'),
        (0, '已执行'),
        (1, '已放弃'),
        (2, '执行失败'),
    )

    # user = models.ManyToManyField(to=User)
    commiter = models.ForeignKey(to=User, related_name='commiter_user', verbose_name='提交人', help_text='SQL提交人')
    treater = models.ForeignKey(to=User, related_name='treater_user', verbose_name='审核人', help_text='审核人，可执行SQL')
    group = models.ForeignKey(to=Group, on_delete=models.CASCADE, verbose_name='审核组', help_text='审核组')
    sql_content = models.TextField(verbose_name='SQL语句', help_text='提交的SQL语句')
    env = models.CharField(verbose_name='执行环境', help_text='执行环境', choices=ENV_TYPE, max_length=12)
    database = models.ForeignKey(to=DatabaseConfig, on_delete=models.CASCADE,
                                 verbose_name='数据库', help_text='连接的执行库')
    status = models.IntegerField(default=-1, choices=STATUS, verbose_name='SQL状态', help_text='SQL状态')
    execute_errors = models.TextField(default='', null=True, blank=True, verbose_name='执行错误')
    exe_affected_rows = models.CharField(max_length=10, null=True, blank=True, verbose_name='执行影响行数')
    roll_affected_rows = models.CharField(max_length=10, null=True, blank=True, verbose_name='回滚影响行数')
    rollback_opid = models.TextField(blank=True, null=True, verbose_name='回滚序列号',
                                     help_text='相应回滚语句的opid，从备份表过滤找到回滚SQL')
    rollback_db = models.CharField(max_length=100, null=True, blank=True, verbose_name='回滚库')
    utime = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    ctime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    remark = models.TextField(default='', null=True, blank=True, verbose_name='备注')

    class Meta:
        ordering = ['-id']
